package com.story.api.moduler.song.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageHelper;
import com.story.api.common.persistence.dao.BannerMapper;
import com.story.api.common.persistence.model.Banner;
import com.story.api.common.persistence.model.VedioCategory;
import com.story.api.common.persistence.model.VedioDetail;
import com.story.api.common.result.PageResult;
import com.story.api.common.result.ServerResponse;
import com.story.api.common.util.PageBeanUtil;
import com.story.api.config.properties.UpyunProperties;
import com.story.api.moduler.song.dao.IndexPictureDao;
import com.story.api.moduler.song.dao.SongCountDao;
import com.story.api.moduler.song.dao.VedioCategoryDao;
import com.story.api.moduler.song.dao.VedioDetailDao;
import com.story.api.moduler.song.service.SongService;
import com.story.api.moduler.song.transfer.vo.AgeSongCountVo;
import com.story.api.moduler.song.transfer.vo.AllSongCountVo;
import com.story.api.moduler.upyun.service.UpyunService;
import com.story.core.util.UriUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 视频相关接口
 * @date 2017年12月11 21:13
 */
@Service
public class SongServiceImpl implements SongService {

    private static final Long EXPIRE_TIME = 3600L;

    @Autowired
    private SongCountDao songCountDao;

    @Autowired
    private VedioDetailDao vedioDetailDao;

    @Autowired
    private BannerMapper bannerMapper;

    @Autowired
    private VedioCategoryDao vedioCategoryDao;

    @Autowired
    private IndexPictureDao indexPictureDao;

    @Autowired
    private UpyunService upyunService;

    @Autowired
    private UpyunProperties upyunProperties;

    /**
     * 首页数据处理
     * @return
     */
    @Override
    public ServerResponse getIndexPage() {
        Map<String,Object> result = new HashMap<String,Object>();
        List<AgeSongCountVo> ageSongCountVoList = songCountDao.getAgeCount();
        //当没有数据时，需要传0
        if(ageSongCountVoList.isEmpty()) {
            AgeSongCountVo ageOne = getNullAgeCount(1);
            result.put("ageOne",ageOne);
            AgeSongCountVo ageOneToThree = getNullAgeCount(2);
            result.put("ageOneToThree",ageOneToThree);
            AgeSongCountVo ageThreeToSix = getNullAgeCount(3);
            result.put("ageThreeToSix",ageThreeToSix);
        } else {
            List<Integer> ageBands = new ArrayList<Integer>();
            for (AgeSongCountVo ageCount:
                    ageSongCountVoList) {
                ageBands.add(ageCount.getAgeBand());
                String pictureUrl = indexPictureDao.getPictureUrlByAgeType(ageCount.getAgeBand());
                if(StringUtils.isBlank(pictureUrl)) {
                    ageCount.setPictureUrl("");
                } else {
                    ageCount.setPictureUrl(addTokenUrl(pictureUrl));
                }
                if(ageCount.getAgeBand() == 1) {
                    ageCount.setAgeTitle("0-1岁");
                    result.put("ageOne",ageCount);
                }
                if(ageCount.getAgeBand() == 2) {
                    ageCount.setAgeTitle("1-3岁");
                    result.put("ageOneToThree",ageCount);
                }
                if(ageCount.getAgeBand() == 3) {
                    ageCount.setAgeTitle("3-6岁");
                    result.put("ageThreeToSix",ageCount);
                }
            }
            if(!ageBands.isEmpty()) {
                for (int i = 1; i <= 3; i++) {
                    if(!ageBands.contains(Integer.valueOf(i))) {
                        AgeSongCountVo ageVo = getNullAgeCount(i);
                        if(i == 1) {
                            result.put("ageOne",ageVo);
                        }
                        if(i == 2) {
                            result.put("ageOneToThree",ageVo);
                        }
                        if(i == 3) {
                            result.put("ageThreeToSix",ageVo);
                        }
                    }
                }
            }
        }

        AllSongCountVo allSongCountVo = songCountDao.getAllCount();
        String pictureUrl = indexPictureDao.getPictureUrlByAgeType(0);
        if(StringUtils.isBlank(pictureUrl)) {
            allSongCountVo.setPictureUrl("");
        } else {
            allSongCountVo.setPictureUrl(addTokenUrl(pictureUrl));
        }
        allSongCountVo.setSongTitle("全部歌曲");
        result.put("allSongCount",allSongCountVo);
        return ServerResponse.getSuccess("success",result);
    }

    /**
     * 首页年龄段点击进入歌曲列表
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public ServerResponse getAgeSongListByPage(Integer currentPage, Integer pageSize,Integer ageType) {
        PageHelper.startPage(currentPage,pageSize);
        List<VedioDetail> vedioDetailList = vedioDetailDao.getVedioDetailByPage(ageType);
        dealVedioDetailList(vedioDetailList);
        PageResult<VedioDetail> pageResult = PageBeanUtil.toPageResult(vedioDetailList);
        return ServerResponse.getSuccess("success",pageResult);
    }

    /**
     * 处理视频详情数据
     * @param vedioDetailList
     */
    public void dealVedioDetailList(List<VedioDetail> vedioDetailList) {
        vedioDetailList.parallelStream().forEach(vedioDetail -> {
            vedioDetail.setPlayCount( RandomUtils.nextInt(5001)+50000);
            vedioDetail.setDownloadCount(RandomUtils.nextInt(51)+100);
            vedioDetail.setShareCount(RandomUtils.nextInt(20)+30);
            if(StringUtils.isNotBlank(vedioDetail.getLogoPath())) {
                vedioDetail.setLogoPath(addTokenUrl(vedioDetail.getLogoPath()));
            }
            if(StringUtils.isNotBlank(vedioDetail.getFilePath())) {
                vedioDetail.setFilePath(videoAddDomain(vedioDetail.getFilePath()));
            }
        });
    }

    /**
     * 得到所有栏目
     * @return
     */
    @Override
    public ServerResponse getAllBanner() {
        //返回媒体资源为视频的栏目
        List<Banner> bannerList = bannerMapper.selectList(new EntityWrapper<Banner>().eq("type",1));
        bannerList.stream().sorted(Comparator.comparing(Banner::getRank).reversed()).limit(4).collect( Collectors.toList());
        bannerList.parallelStream().forEach( banner -> {
            if (StringUtils.isNotBlank(banner.getIconPath())) {
                banner.setIconPath(addTokenUrl(banner.getIconPath()));
            }
        });
        return ServerResponse.getSuccess("success",bannerList);
    }

    /**
     * 通过bannerId得到banner下对应的专辑分页数据
     * @param currentPage
     * @param pageSize
     * @param bannerId
     * @return
     */
    @Override
    public ServerResponse getCateListPage(Integer currentPage, Integer pageSize, Integer bannerId) {
        PageHelper.startPage(currentPage,pageSize);
        List<VedioCategory> categoryList = vedioCategoryDao.getvedioCategoryPage(bannerId);
        categoryList.parallelStream().forEach(vedioCategory -> {
            if(StringUtils.isNotBlank(vedioCategory.getIconPath())) {
                vedioCategory.setIconPath(addTokenUrl(vedioCategory.getIconPath()));
            }
        });
        PageResult<VedioCategory> pageResult = PageBeanUtil.toPageResult(categoryList);
        return ServerResponse.getSuccess("success",pageResult);
    }

    /**
     * 专辑下的视频列表分页数据
     * @param currentPage
     * @param pageSize
     * @param cateId
     * @return
     */
    @Override
    public ServerResponse getVedioDetailPage(Integer currentPage, Integer pageSize, Integer cateId) {
        PageHelper.startPage(currentPage,pageSize);
        List<VedioDetail> vedioDetailList = vedioDetailDao.getVedioDetaiPageByCateId(cateId);
        dealVedioDetailList(vedioDetailList);
        PageResult<VedioDetail> pageResult = PageBeanUtil.toPageResult(vedioDetailList);
        return ServerResponse.getSuccess("success",pageResult);
    }

    /**
     * 得到随意两个专辑数据
     * @param bannerId
     * @return
     */
    @Override
    public ServerResponse getGuessYouLikeCate(Integer bannerId) {
        List<VedioCategory> vedioCategoryList = vedioCategoryDao.getVedioCategoryByBannerId(bannerId);
        vedioCategoryList.parallelStream().forEach( vedioCategory -> {
            if(StringUtils.isNotBlank(vedioCategory.getIconPath())) {
                vedioCategory.setIconPath(addTokenUrl(vedioCategory.getIconPath()));
            }
        });
        int length = vedioCategoryList.size();
        int one = RandomUtils.nextInt(length);
        int two = RandomUtils.nextInt(length);
        while(one == two) {
            two = RandomUtils.nextInt(length);
        }
        List<VedioCategory> veilCategories = new ArrayList<VedioCategory>();
        veilCategories.add(vedioCategoryList.get(one));
        veilCategories.add(vedioCategoryList.get(two));
        return ServerResponse.getSuccess("success",veilCategories);
    }

    /**
     * 热门搜索
     * @return
     */
    @Override
    public ServerResponse getHotVedios(Integer version) {
        List<VedioDetail> vedioDetailList = vedioDetailDao.getHotVedio(version);
        vedioDetailList.parallelStream().forEach(vedioDetail -> {
            if(StringUtils.isNotBlank(vedioDetail.getLogoPath())) {
                vedioDetail.setLogoPath(addTokenUrl(vedioDetail.getLogoPath()));
            }
            if(StringUtils.isNotBlank(vedioDetail.getFilePath())) {
                vedioDetail.setFilePath(videoAddDomain(vedioDetail.getLogoPath()));
            }
        });
        return ServerResponse.getSuccess("success",vedioDetailList);
    }

    /**
     * 搜索
     * @param keyword
     * @return
     */
    @Override
    public ServerResponse getSearchPage(Integer currentPage,Integer pageSize,String keyword,Integer versionFlag) {
        PageHelper.startPage(currentPage,pageSize);
        List<VedioDetail> vedioDetailList = vedioDetailDao.getSearchVedioPage(keyword,versionFlag);
        dealVedioDetailList(vedioDetailList);
        PageResult<VedioDetail> pageResult = PageBeanUtil.toPageResult(vedioDetailList);
        return  ServerResponse.getSuccess("success",pageResult);
    }

    /**
     * 对url添加token,防止盗链
     * @param url
     * @return
     */
    private String addTokenUrl(String url) {
        return upyunProperties.getDomain() + url + "?_upt=" + upyunService.getTokenSign(UriUtil.getUri(url),EXPIRE_TIME);
    }

    /**
     * 对于视频只添加域名
     * @param url
     * @return
     */
    private String videoAddDomain(String url) {
        return upyunProperties.getDomain() + url;
    }

    /**
     * 处理无此年龄段的极端情况
     * @param ageBand
     * @return
     */
    private AgeSongCountVo getNullAgeCount(int ageBand) {
        AgeSongCountVo ageSongCountVo = new AgeSongCountVo();
        ageSongCountVo.setAgeBand(ageBand);
        if(ageBand == 1) {
            ageSongCountVo.setAgeTitle("0-1岁");
        }
        if(ageBand == 2) {
            ageSongCountVo.setAgeTitle("1-3岁");
        }
        if(ageBand == 3) {
            ageSongCountVo.setAgeTitle("3-6岁");
        }
        String pictureUrl = StringUtils.isBlank(indexPictureDao.getPictureUrlByAgeType(ageBand)) ? "" : addTokenUrl(indexPictureDao.getPictureUrlByAgeType(ageBand));
        ageSongCountVo.setPictureUrl(pictureUrl);
        ageSongCountVo.setSongCount(0);
        ageSongCountVo.setUpdateCount(0);
        return ageSongCountVo;
    }

}
